<template>
  <div class="app-container">
    <el-form
      class="searchform"
      :model="queryParams"
      size="small"
      :inline="true"
    >
      <el-form-item label="申请人">
        <el-input
          style="width: 200px"
          v-model="queryParams.applyUserName"
          placeholder="请输入"
          @keyup.enter.native="handleSearch"
        ></el-input>
      </el-form-item>
      <el-form-item label="申请部门:">
        <el-select
          style="width: 300px"
          v-model="queryParams.applyDept"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in saleDeptList"
            :key="index"
            :label="item.deptName"
            :value="item.deptId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审批人">
        <el-input
          style="width: 200px"
          v-model="queryParams.approveUserName"
          placeholder="请输入"
          @keyup.enter.native="handleSearch"
        ></el-input>
      </el-form-item>
      <el-form-item label="申请日期">
        <el-date-picker
          style="width: 250px"
          v-model="queryParams.applyDate"
          type="daterange"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="客户">
        <OrganizationSelect
          style="width: 300px"
          v-model="queryParams.entrustOrganizationId"
        ></OrganizationSelect>
      </el-form-item>
      <el-form-item label="发票号码">
        <el-input
          style="width: 200px"
          v-model="queryParams.invoiceNumber"
          placeholder="请输入"
          @keyup.enter.native="handleSearch"
        ></el-input>
      </el-form-item>
      <el-form-item label="发票抬头">
        <el-select
          style="width: 300px"
          v-model="queryParams.invoiceHeaderId"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in invoiceHeaderList"
            :key="index"
            :label="item.companyName"
            :value="item.invoiceHeaderId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          style="width: 200px"
          v-model="queryParams.applyState"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in dict.type.invoice_apply_state"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label=" " label-width="20px">
        <el-button type="primary" icon="el-icon-search" @click="handleSearch"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-wrapper">
      <div class="tableoperation">
        <el-button
          type="primary"
          v-hasPermi="['basic:invoiceApply:add']"
          icon="el-icon-plus"
          @click="handleAddInvoicing"
          >新增开票申请</el-button
        >
      </div>

      <el-table v-loading="tableLoading" height="300px" :data="tableList">
        <el-table-column
          label="申请日期/编号"
          align="center"
          prop=""
          min-width="120"
        >
          <template slot="header">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <SortIcon prop="createTime" @sort-change="handleSortChange" />
              <span style="line-height: 1">申请日期/编号</span>
            </div>
          </template>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
            <br />
            <span>{{ scope.row.applyNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="申请人/部门"
          align="center"
          prop=""
          min-width="240"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.applyUserName }}</span>
            <br />
            <span>{{ scope.row.applyDeptName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="客户/抬头"
          align="center"
          prop=""
          min-width="200"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.entrustOrganizationName }}</span>
            <br />
            <span>{{ scope.row.invoiceHeaderName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="申请金额/税率"
          align="center"
          prop=""
          min-width="120"
        >
          <template slot="header">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <SortIcon prop="totalAmount" @sort-change="handleSortChange" />
              <span style="line-height: 1">申请金额/税率</span>
            </div>
          </template>
          <template slot-scope="scope">
            <span>{{ scope.row.totalAmount }}</span>
            <br />
            <span>{{ scope.row.taxRate || "--" }}%</span>
          </template>
        </el-table-column>
        <el-table-column
          label="发票号码"
          align="center"
          prop="invoiceNumber"
          min-width="100"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.invoiceNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="开票日期"
          align="center"
          prop="invoiceDate"
          min-width="100"
        >
          <template slot="header">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <span style="line-height: 1">开票日期</span>
              <SortIcon prop="invoiceDate" @sort-change="handleSortChange" />
            </div>
          </template>
          <template slot-scope="scope">
            <span>{{ scope.row.invoiceDate }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          align="center"
          prop="applyState"
          min-width="100"
        >
          <template slot="header">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <span style="line-height: 1">状态</span>
              <SortIcon
                :prop="'stateSortOrder'"
                @sort-change="handleSortChange"
              />
            </div>
          </template>
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.invoice_apply_state"
              :value="scope.row.applyState"
            />
          </template>
        </el-table-column>
        <el-table-column label="审批人" align="center" prop="" min-width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.approveUserName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          align="center"
          prop="remark"
          min-width="120"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" prop="" width="120">
          <template slot-scope="scope">
            <el-link type="primary" @click="handleLookInvoicing(scope.row)"
              >查看</el-link
            >
            <!-- 草稿状态 || 审核不通过 才能修改 -->
            <el-link
              style="margin-left: 10px"
              type="primary"
              @click="handleEditInvoicing(scope.row)"
              v-if="
                checkPermi(['basic:invoiceApply:edit']) &&
                (scope.row.applyState == 0 || scope.row.applyState == -1) &&
                scope.row.beOperate
              "
              >修改</el-link
            >
            <!-- 非草稿状态 才能撤销 -->
            <el-link
              style="margin-left: 10px"
              type="primary"
              @click="handleRevokeInvoicing(scope.row)"
              v-if="
                checkPermi(['basic:invoiceApply:cancel']) &&
                scope.row.applyState != 0 &&
                scope.row.beOperate
              "
              >撤销</el-link
            >
            <!-- 草稿状态 才能删除 -->
            <el-link
              style="margin-left: 10px"
              type="danger"
              @click="handleDeleteInvoicing(scope.row)"
              v-if="
                checkPermi(['basic:invoiceApply:delete']) &&
                scope.row.applyState == 0 &&
                scope.row.beOperate
              "
              >删除</el-link
            >
            <!-- 待审批状态才能审批 && 有审批标识 -->
            <el-link
              style="margin-left: 10px"
              type="primary"
              @click="handleApproInvoicing(scope.row)"
              v-if="
                checkPermi(['basic:invoiceApply:approve']) &&
                scope.row.applyState == 1 &&
                (scope.row.beApprove || scope.row.beOperate)
              "
              >审批</el-link
            >
            <!-- 待开票状态才能开票 -->
            <el-link
              style="margin-left: 10px"
              type="primary"
              @click="handleInvoiceInvoicing(scope.row)"
              v-if="
                checkPermi(['basic:invoiceApply:invoice']) &&
                scope.row.applyState == 2 &&
                scope.row.beOperate
              "
              >开票</el-link
            >
          </template>
        </el-table-column>
      </el-table>

      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div style="color: #555; font-size: 15px">
          <span>金额合计：{{ tableCountData.totalAmountCount }}</span>
        </div>

        <pagination
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          :total="tableTotal"
          @pagination="getTableListData"
        ></pagination>
      </div>
    </div>

    <!-- 新增/修改 开票申请弹框 -->
    <AddEditInvoicingDialog
      :show.sync="showAddEditInvoicingDialog"
      :operType="operType"
      :row="currRow"
      @refresh="getTableListData"
    ></AddEditInvoicingDialog>

    <!-- 撤销弹框 -->
    <RevokeInvoicingDialog
      :show.sync="showRevokeInvoicingDialog"
      :row="currRow"
      @refresh="getTableListData"
    ></RevokeInvoicingDialog>

    <!-- 审批弹框 -->
    <ApproveInvoicingDialog
      :show.sync="showApproveInvoicingDialog"
      :row="currRow"
      @refresh="getTableListData"
      @supple="handleSupple"
    ></ApproveInvoicingDialog>
  </div>
</template>

<script>
import AddEditInvoicingDialog from "./components/AddEditInvoicingDialog.vue";
import RevokeInvoicingDialog from "./components/RevokeInvoicingDialog.vue";
import ApproveInvoicingDialog from "./components/ApproveInvoicingDialog.vue";
import { listDeptIgnorePermission } from "@/api/system/dept";
import { invoiceListAll } from "@/api/person/invoice";
import {
  invoicingList,
  genInvoicingCount,
  invoicingDelete,
  invoicingOper,
} from "@/api/person/invoicing";
import SortIcon from "./components/sortIcon";

export default {
  name: "invoicing",
  dicts: ["invoice_apply_state"],
  components: {
    AddEditInvoicingDialog,
    RevokeInvoicingDialog,
    ApproveInvoicingDialog,
    SortIcon,
  },
  data() {
    return {
      saleDeptList: [],
      invoiceHeaderList: [],
      queryParams: {},
      tableLoading: false,
      tableList: [],
      tableTotal: 0,
      tableCountData: {},

      showAddEditInvoicingDialog: false,
      currRow: {},
      operType: "add",

      showRevokeInvoicingDialog: false,

      showApproveInvoicingDialog: false,
    };
  },
  created() {
    this.getApplyDeptList();
    this.getInvoiceHeaderList();
    this.initQueryParams();
    this.getTableListData();
  },
  methods: {
    // 获取申请部门列表
    getApplyDeptList() {
      listDeptIgnorePermission({
        pageNum: 1,
        pageSize: 10000,
        parentId: 0,
      })
        .then((res) => {
          this.saleDeptList = res.data || [];
        })
        .catch((err) => {});
    },
    // 获取发票抬头列表
    getInvoiceHeaderList() {
      invoiceListAll()
        .then((res) => {
          this.invoiceHeaderList = res.data || [];
        })
        .catch((err) => {});
    },
    // 初始化查询参数
    initQueryParams() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        applyUserName: "",
        applyDept: "",
        approveUserName: "",
        applyDate: [],
        entrustOrganizationId: "",
        invoiceNumber: "",
        invoiceHeaderId: "",
        applyState: "",
        orderByColumn: "stateSortOrder",
        isAsc: "ascending",
      };
    },
    // 获取查询参数
    getQueryParams() {
      const params = JSON.parse(JSON.stringify(this.queryParams));
      params.applyBeginDate = params.applyDate ? params.applyDate[0] : "";
      params.applyEndDate = params.applyDate ? params.applyDate[1] : "";
      delete params.applyDate;
      return params;
    },
    // 获取表格数据
    getTableListData() {
      this.tableLoading = true;
      const params = this.getQueryParams();
      invoicingList(params)
        .then((res) => {
          this.tableLoading = false;
          this.tableList = res.rows || [];
          this.tableTotal = res.total || 0;
        })
        .catch((err) => {
          this.tableLoading = false;
        });
      this.genContractCountData();
    },
    // 获取表格统计数据
    genContractCountData() {
      const params = this.getQueryParams();
      delete params.pageNum;
      delete params.pageSize;
      genInvoicingCount(params)
        .then((res) => {
          this.tableCountData = res.data || {};
          console.log("tableCountData", this.tableCountData);
        })
        .catch((err) => {});
    },
    // 排序
    handleSortChange({ prop, order }) {
      this.queryParams.orderByColumn = prop;
      this.queryParams.isAsc = order;
      this.getTableListData();
    },
    // 点击搜索
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.getTableListData();
    },
    // 点击重置
    handleReset() {
      this.initQueryParams();
      this.getTableListData();
    },
    // 点击查看开票申请
    handleLookInvoicing(row) {
      this.operType = "detail";
      this.currRow = row;
      this.showAddEditInvoicingDialog = true;
    },
    // 点击新增开票申请
    handleAddInvoicing() {
      this.operType = "add";
      this.showAddEditInvoicingDialog = true;
    },
    // 点击修改开票申请
    handleEditInvoicing(row) {
      this.operType = "edit";
      this.currRow = row;
      this.showAddEditInvoicingDialog = true;
    },
    // 点击补录开票信息
    handleSupple() {
      this.operType = "update";
      this.showAddEditInvoicingDialog = true;
    },
    // 点击撤销开票申请
    handleRevokeInvoicing(row) {
      this.currRow = row;
      this.showRevokeInvoicingDialog = true;
    },
    // 点击删除开票申请
    handleDeleteInvoicing(row) {
      this.$modal
        .confirm("是否确认删除该开票申请?")
        .then(() => {
          return invoicingDelete(row.invoiceApplyId);
        })
        .then(() => {
          this.getTableListData();
          this.$modal.msgSuccess("删除成功");
        })
        .catch((err) => {});
    },
    // 点击审批
    handleApproInvoicing(row) {
      this.currRow = row;
      this.showApproveInvoicingDialog = true;
    },
    // 点击开票
    handleInvoiceInvoicing(row) {
      this.$modal
        .confirm("是否确认开票?")
        .then(() => {
          return invoicingOper({ invoiceApplyId: row.invoiceApplyId });
        })
        .then(() => {
          this.$modal.msgSuccess("操作成功");
          this.getTableListData();
        })
        .catch((err) => {});
    },
  },
};
</script>

<style scoped lang="scss">
.app-container {
}
</style>
